package org.example.blogserver.service.impl;

import org.example.blogserver.dao.ArticleDao;
import org.example.blogserver.entity.Article;
import org.example.blogserver.entity.SysUser;
import org.example.blogserver.handler.TokenManager;
import org.example.blogserver.service.ArticleService;
import org.example.blogserver.service.SysUserService;
import org.example.blogserver.utils.DateUtil;
import org.example.blogserver.vo.ArticleMessage;
import org.example.blogserver.vo.ArticleVo;
import org.example.blogserver.vo.Result;
import org.example.blogserver.vo.UserVo;
import org.example.blogserver.vo.params.ArticleIdParam;
import org.example.blogserver.vo.params.ArticleParam;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

@Service
public class ArticleServiceImpl implements ArticleService {


    @Autowired
    private SysUserService sysUserService;
    @Autowired
    private ArticleDao articleDao;
    @Autowired
    private StringRedisTemplate redisTemplate;
    @Autowired
    private TokenManager tokenManager;
//    @Autowired
//    private RocketMQTemplate rocketMQTemplate;

    @Override
    public Result addArticle(String token, ArticleParam articleParam) {
    // 验证 token 是否有效
    String account = tokenManager.getAccountFromToken(token);
    if (account == null) {
        return Result.fail(400, "登录过期，请重新登录！");
    }
    Article article = new Article();
    article = new Article();
    article.setAuthorAccount(account);
    article.setViewCounts(0);
    article.setLikeCounts(0);
    article.setTitle(articleParam.getTitle());
    article.setSummary(articleParam.getSummary());
    article.setBody(articleParam.getBody());
    article.setCommentCounts(0);
    article.setCreateDate(System.currentTimeMillis());
    article.setPublic(articleParam.is_public());
    //插入之后 会生成一个文章id
    this.articleDao.addArticle(article);


    //发送一条消息给rocketmq 当前文章更新了，更新一下缓存吧
    ArticleMessage articleMessage = new ArticleMessage();
    articleMessage.setArticleId(article.getId());
    return Result.success("发布成功！",null);
}

    @Override
    public Result deleteArticleById(String token, Long id) {
        // 验证 token 是否有效
        String account = tokenManager.getAccountFromToken(token);
        if (account == null) {
            return Result.fail(400, "登录过期，请重新登录！");
        }
        int result = articleDao.deleteArticleById(id);
        if (result > 0) {
            return Result.success("删除成功！",null);
        } else {
            return Result.fail(500, "删除失败！");
        }
    }

    @Override
    public Result updateArticle(String token, ArticleIdParam articleIdParam) {
        // 验证 token 是否有效
        String account = tokenManager.getAccountFromToken(token);
        if (account == null) {
            return Result.fail(400, "登录过期，请重新登录！");
        }
        Article article = new Article();
        article.setId(articleIdParam.getId());
        article.setTitle(articleIdParam.getTitle());
        article.setSummary(articleIdParam.getSummary());
        article.setBody(articleIdParam.getBody());
        article.setPublic(articleIdParam.is_public());
        this.articleDao.updateArticle(article);

        //发送一条消息给rocketmq 当前文章更新了，更新一下缓存吧
        ArticleMessage articleMessage = new ArticleMessage();
        articleMessage.setArticleId(article.getId());
        return Result.success("发布成功！",null);
    }

    @Override
    public Result findArticleVoById(Long articleId) {

        Article article = this.articleDao.findArticleById(articleId);
        ArticleVo articleVo = convertToArticleVo(article);
        return Result.success("查询成功！",articleVo);
    }
    @Override
    public Result findArticlesByAuthorAccount(String authorAccount) {
        List<Article> articleList = this.articleDao.findArticlesByAuthorAccount(authorAccount);
        List<ArticleVo> articleVoList = convertToArticleVoList(articleList);

        return Result.success("查询成功！",articleVoList);
    }

    @Override
    public Result findArticlesByIsPublic(boolean isPublic) {
        List<Article> articleList = this.articleDao.findArticlesByIsPublic(isPublic);
        List<ArticleVo> articleVoList = convertToArticleVoList(articleList);

        return Result.success("查询成功！",articleVoList);
    }

    @Override
    public Result addLike(Long articleId) {
        int result = articleDao.addLike(articleId);
        if (result > 0) {
            return Result.success("点赞成功！",null);
        } else {
            return Result.fail(500, "点赞失败！");
        }
    }
    @Override
    public Result addView(Long articleId) {
        int result = articleDao.addView(articleId);
        if (result > 0) {
            return Result.success("",null);
        } else {
            return Result.fail(500, "");
        }
    }


    public  ArticleVo convertToArticleVo(Article article) {
        ArticleVo articleVo = new ArticleVo();
        // 使用Spring的BeanUtils将属性值复制到ArticleVo对象中
        BeanUtils.copyProperties(article, articleVo);
        // 检查 createDate 是否为空
        if (article.getCreateDate() != null) {
            articleVo.setCreateDate(DateUtil.longToString(article.getCreateDate(),"yyyy-MM-dd HH:mm:ss"));
        } else {
            articleVo.setCreateDate(null);
        }
        // 设置作者信息
        UserVo author=sysUserService.getUserVoByAccount(article.getAuthorAccount());
        articleVo.setAuthor(author);
        String viewCount = (String) redisTemplate.opsForHash().get("view_count", String.valueOf(article.getId()));
        if (viewCount != null){
            articleVo.setViewCounts(Integer.parseInt(viewCount));
        }
        String likeCount = (String) redisTemplate.opsForHash().get("like_count", String.valueOf(article.getId()));
        if (likeCount != null){
            articleVo.setLikeCounts(Integer.parseInt(likeCount));
        }
        String commentCount = (String) redisTemplate.opsForHash().get("comment_count", String.valueOf(article.getId()));
        if (commentCount != null){
            articleVo.setCommentCounts(Integer.parseInt(commentCount));
        }
        return articleVo;
    }
    public  List<ArticleVo> convertToArticleVoList(List<Article> articleList) {
        List<ArticleVo> articleVoList = new ArrayList<>();
        for (Article article : articleList) {
            ArticleVo articleVo = convertToArticleVo(article);
            articleVoList.add(articleVo);
        }
        return articleVoList;
    }
}
